//
//  CYYaoQingHuiDaTuiJianViewController.m
//  cyydt
//
//  Created by chu on 2019/2/3.
//  Copyright © 2019 chu. All rights reserved.
//

#import "CYYaoQingHuiDaTuiJianViewController.h"
#import "CYMine_FriendTableViewCell.h"
#import "CYFriendModel.h"
#import "CYHuiDaTuiJianView.h"

@interface CYYaoQingHuiDaTuiJianViewController ()<UITableViewDelegate, UITableViewDataSource, DZNEmptyDataSetSource, DZNEmptyDataSetDelegate, PlatformButtonClickDelegate>
{
    UIImage *_shareImage;
}
@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic, strong) NSMutableArray *dataSourceArr;

@property (nonatomic, strong) UIView *tableHeaderView;


@end

@implementation CYYaoQingHuiDaTuiJianViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.automaticallyAdjustsScrollViewInsets = NO;

//    [self.view addSubview:self.tableView];
    [self getData];
    if (@available(iOS 11.0, *)) {
        self.tableView.estimatedSectionFooterHeight = 0;
        self.tableView.estimatedSectionHeaderHeight = 0;
        self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }else{
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    if (self.model.img_url.count > 0) {
        NSString *url = [self.model.img_url firstObject];
        [[SDWebImageDownloader sharedDownloader] downloadImageWithURL:[NSURL URLWithString:url] options:0 progress:^(NSInteger receivedSize, NSInteger expectedSize, NSURL * _Nullable targetURL) {
            
        } completed:^(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, BOOL finished) {
            self->_shareImage = image;
        }];
    }
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataSourceArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    CYMine_FriendTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CYMine_FriendTableViewCell"];
    if (!cell) {
        cell = [[NSBundle mainBundle] loadNibNamed:@"CYMine_FriendTableViewCell" owner:nil options:nil][0];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    CYFriendModel *model = self.dataSourceArr[indexPath.row];
    cell.yaoqingModel = model;
    cell.block = ^{
        if ([model.isInvite integerValue] == 0) {
            //未邀请
            [self yaoqingWithUserId:model.userId];
        }
    };
    return cell;
}

#pragma mark - 邀请回答
- (void)yaoqingWithUserId:(NSNumber *)userid{
    [EasyShowLodingView showLoding];
    NSString *url = [NSString stringWithFormat:@"%@%@",User_HOST, @"ask/invite"];
    NSDictionary *param = @{@"userId":userid, @"questionId":self.questionId};
    [[XBRequest sharedInstance] postDataWithUrl:url Parameter:param ResponseObject:^(NSDictionary *responseResult) {
        [EasyShowLodingView hidenLoding];
        NSLog(@"邀请回答 ---- %@",responseResult);
        if ([responseResult objectForKey:@"resError"]) {
            [self.view makeToast:ResErrorMessage];
        }else{
            if ([responseResult[Response_code] integerValue] == Response_value) {
                [self getData];
                [[UIApplication sharedApplication].keyWindow makeToast:responseResult[Response_Message] duration:1.5 position:CSToastPositionCenter];
            }else{
                [[UIApplication sharedApplication].keyWindow makeToast:responseResult[Response_Message] duration:1.5 position:CSToastPositionCenter];
                
            }
        }
    }];
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 80;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.0001f;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *view = [[UIView alloc] init];
    return view;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.0001f;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView *view = [[UIView alloc] init];
    return view;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    CYFriendModel *model = self.dataSourceArr[indexPath.row];

    CYGeRenZhuYeViewController *zhuye = [[CYGeRenZhuYeViewController alloc] init];
    zhuye.userId = model.userId;

    [[AppDelegate sharedAppDelegate] pushViewController:zhuye];
}

- (void)getData{
    self.page = 1;
    NSString *url = [NSString stringWithFormat:@"%@%@",User_HOST, @"user/categoryExpert"];

    NSDictionary *param = @{@"questionId":self.questionId, @"pageNo":@1, @"id":self.cateId};
    [[XBRequest sharedInstance] getDataWithUrl:url Parameter:param ResponseObject:^(NSDictionary *responseResult) {
        NSLog(@"好友列表 ---- %@",responseResult);
        [self.tableView removeFromSuperview];
        [self.view addSubview:self.tableView];
        if ([self.tableView.mj_header isRefreshing]) {
            [self.tableView.mj_header endRefreshing];
        }
        if ([responseResult objectForKey:@"resError"]) {
            [self.view makeToast:ResErrorMessage];
        }else{
            if ([responseResult[Response_code] integerValue] == Response_value) {
                NSArray *data = responseResult[@"data"];
                [self.dataSourceArr removeAllObjects];
                for (NSDictionary *dic in data) {
                    CYFriendModel *model = [CYFriendModel mj_objectWithKeyValues:dic];
                    [self.dataSourceArr addObject:model];
                }
            }else{
                [self.view makeToast:responseResult[Response_Message] duration:1.5 position:CSToastPositionCenter];
            }
        }
        [self.tableView reloadData];

    }];
}

- (void)getMoreData{
    self.page ++;
    NSString *url = [NSString stringWithFormat:@"%@%@",User_HOST, @"user/categoryExpert"];
    NSDictionary *param = @{@"questionId":self.questionId, @"pageNo":[NSNumber numberWithInteger:self.page], @"id":self.cateId};
    [[XBRequest sharedInstance] getDataWithUrl:url Parameter:param ResponseObject:^(NSDictionary *responseResult) {
        NSLog(@"首页推荐 ---- %@",responseResult);
        if ([self.tableView.mj_footer isRefreshing]) {
            [self.tableView.mj_footer endRefreshing];
        }
        if ([responseResult objectForKey:@"resError"]) {
            [self.view makeToast:ResErrorMessage];
            self.page -- ;
        }else{
            if ([responseResult[Response_code] integerValue] == Response_value) {
                NSArray *data = responseResult[@"data"];
                for (NSDictionary *dic in data) {
                    CYFriendModel *model = [CYFriendModel mj_objectWithKeyValues:dic];
                    [self.dataSourceArr addObject:model];
                }
                [self.tableView reloadData];
            }else{
                self.page -- ;
                [self.view makeToast:responseResult[Response_Message] duration:1.5 position:CSToastPositionCenter];
            }
        }
    }];
}

#pragma mark - DZNEmptyDataSetDelegate
- (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView {
    return [UIImage imageNamed:@"wuneir"];
}

- (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView {
    NSString *title = @"当前页面没有内容！";
    NSDictionary *attributes = @{
                                 NSFontAttributeName:[UIFont boldSystemFontOfSize:16],NSForegroundColorAttributeName:RGBOF(0x999999)
                                 };
    return [[NSAttributedString alloc] initWithString:title attributes:attributes];
}

- (void)emptyDataSet:(UIScrollView *)scrollView didTapView:(UIView *)view {
    // 空白页面被点击时开启动画，reloadEmptyDataSet
    [self getData];
}

- (UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kWindowW, kWindowH - Height_NavBar) style:UITableViewStyleGrouped];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.backgroundColor = BackGroundColor;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.tableHeaderView = self.tableHeaderView;
        _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            [self getData];
        }];
        _tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
            [self getMoreData];
        }];
        _tableView.emptyDataSetSource = self;
        _tableView.emptyDataSetDelegate = self;
        
        [_tableView registerNib:[UINib nibWithNibName:@"CYMine_FriendTableViewCell" bundle:nil] forCellReuseIdentifier:@"CYMine_FriendTableViewCell"];
    }
    return _tableView;
}

- (NSMutableArray *)dataSourceArr{
    if (!_dataSourceArr) {
        _dataSourceArr = [NSMutableArray arrayWithCapacity:0];
    }
    return _dataSourceArr;
}

- (UIView *)tableHeaderView{
    if (!_tableHeaderView) {
        _tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kWindowW, 165)];
        NSArray *nibView =  [[NSBundle mainBundle] loadNibNamed:@"View" owner:self options:nil];
        
        CYHuiDaTuiJianView *headView = [nibView objectAtIndex:0];
        headView.frame = CGRectMake(0, 0, kWindowW, 165);
        __weak typeof(self)weakself = self;
        headView.yaoqingBlock = ^{
            YSActionSheetView * ysSheet=[[YSActionSheetView alloc]initNYSView];
            ysSheet.delegate=self;
            [[UIApplication sharedApplication].keyWindow addSubview:ysSheet];
        };
        headView.closeBlock = ^{
            weakself.tableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kWindowW, 1)];
            [weakself.tableView reloadData];
        };
        [_tableHeaderView addSubview:headView];
    }
    return _tableHeaderView;
}

- (void) customActionSheetButtonClick:(YSActionSheetButton *) btn
{
    [self shareImageToPlatformType:btn.tag];
}

- (void)shareImageToPlatformType:(NSInteger)platformType
{
    //2:qq 3:qzone 0:weixin 1:pengyouquan
    //创建分享消息对象
    if (platformType == 2 || platformType == 3) {
        
        NSString *utf8String = self.model.share_url;
        NSString *title = self.model.title;
        NSString *shareContent = @"";
        if ([NSString stringIsNull:self.model.shareContent]) {
            shareContent = self.model.shareContent;
        }else{
            shareContent = [NSString stringWithFormat:@"%@个回答，%@人收藏", self.model.answer_number, self.model.collect_number];
        }
        NSString *description = shareContent;
        UIImage *image = nil;
        if (!_shareImage) {
            image = [UIImage imageNamed:@"login_logo"];
        }else{
            image = _shareImage;
        }
        QQApiNewsObject *newsObj = [QQApiNewsObject
                                    objectWithURL:[NSURL URLWithString:utf8String] title:title description:description previewImageData:UIImageJPEGRepresentation(image, 1)];
        SendMessageToQQReq *req = [SendMessageToQQReq reqWithContent:newsObj];
        if (platformType == 2) {
            //将内容分享到qq
            [QQApiInterface sendReq:req];
        }else{
            //将内容分享到qzone
            [QQApiInterface SendReqToQZone:req];
        }
        
    }else{
        SendMessageToWXReq *req1 = [[SendMessageToWXReq alloc]init];
        // 是否是文档
        req1.bText =  NO;
        
        //    WXSceneSession  = 0,        /**< 聊天界面    */
        //    WXSceneTimeline = 1,        /**< 朋友圈      */
        //    WXSceneFavorite = 2,
        
        
        req1.scene = (int)platformType;
        
        //创建分享内容对象
        WXMediaMessage *urlMessage = [WXMediaMessage message];
        urlMessage.title = self.model.title;//分享标题
        NSString *shareContent = @"";
        if ([NSString stringIsNull:self.model.shareContent]) {
            shareContent = self.model.shareContent;
        }else{
            shareContent = [NSString stringWithFormat:@"%@个回答，%@人收藏", self.model.answer_number, self.model.collect_number];
        }
        urlMessage.description = shareContent;//分享描述
        if (!_shareImage) {
            [urlMessage setThumbImage:[UIImage imageNamed:@"login_logo"]];//分享图片,使用SDK的setThumbImage方法可压缩图片大小
        }else{
            [urlMessage setThumbImage:_shareImage];//分享图片,使用SDK的setThumbImage方法可压缩图片大小
        }
        
        //创建多媒体对象
        WXWebpageObject *webObj = [WXWebpageObject object];
        webObj.webpageUrl = self.model.share_url;//分享链接
        
        //完成发送对象实例
        urlMessage.mediaObject = webObj;
        req1.message = urlMessage;
        
        //发送分享信息
        [WXApi sendReq:req1];
        
    }
}

@end
